﻿var CardValidationClientSideHide = false;
var PageNumber = 1;
var IsSearchView = false;
var CardIDView = 0;
var IsDeleteView = false;
var CardAutoComElem = null;
var CardAutoComElemVal = null;
var CardTimerId = null;
$(document).ready(function () {
    var path = window.location.pathname;
    if (path.indexOf("SetupCard") != -1) {
        jQuery.validator.addMethod("SetupCreditCardRequireds", jQuery.validator.methods.required, Messages["SetupCreditCardRequireds"]);
        jQuery.validator.addMethod("SetupCreditCardMaxLength100", jQuery.validator.methods.maxlength, Messages["SetupCreditCardMaxLength100"]);
        jQuery.validator.addMethod("SetupCreditCardDate", jQuery.validator.methods.datePicker, Messages["SetupCreditCardDate"]);
        jQuery.validator.addMethod("SetupCreditCardAmexCreditCardNumber", jQuery.validator.methods.creditcardamex, Messages["SetupCreditCardAmexCreditCardNumber"]);
        jQuery.validator.addMethod("SetupCreditCardVisaCreditCardNumber", jQuery.validator.methods.creditcardVisa, Messages["SetupCreditCardVisaCreditCardNumber"]);
        jQuery.validator.addMethod("SetupCreditCardMasterCardCreditCardNumber", jQuery.validator.methods.creditcardMasterCard, Messages["SetupCreditCardMasterCardCreditCardNumber"]);
        $.validator.addClassRules({
            Required: {
                SetupCreditCardRequireds: true,
            },
            MaxLength100: {
                SetupCreditCardMaxLength100: 100,
            },
            Date: {
                SetupCreditCardDate: true,
            },
            CreditCardAmex: {
                SetupCreditCardAmexCreditCardNumber: true,
            },
            CreditCardVisa: {
                SetupCreditCardVisaCreditCardNumber: true,
            },
            CreditCardMasterCard: {
                SetupCreditCardMasterCardCreditCardNumber: true,
            },
        });

        $('#LoadCardDetailsForm').validate();
        LoadCardGrid();
    }
});
$(document).on('change', '.ChangedCardElements', function () {
    $('#CardDetailsSaveBtn').addClass('BackColorRed');
});
$(document).on('change', '.CCardAddElementChange', function () {
    $('#CardAddBtn').addClass('BackColorRed');
});
function DeleteCard(CardID) {
    jConfirm('Are you sure you want to delete this Credit Card?', 'Warning!', function (retVal) {
        if (retVal == true) {
            CardIDView = CardID;
            IsDeleteView = true;
            LoadCardGrid();
        }
    });
}
function AddNewCard() {
    CardValidationClientSideHide = false;
    $.ajax({
        url: urls["SetupAddNewCard"],
        type: 'GET',
        success: function (data) {
            $("#AddNewCardDiv").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            IsDeleteView = false;
            AddNewCardPopUp("AddNewCardDiv");
        }
    });
}
$(document).on('click', '#CardMoreBtn', function () {
    PageNumber = PageNumber + 1;
    IsDeleteView = false;
    LoadCardGrid();
});
$(document).on('click', '#CardSearchBtn', function () {
    IsSearchView = true;
    IsDeleteView = false;
    LoadCardGrid();
});
function AddNewCardPopUp(PopUpDiv) {
    $.colorbox({
        width: "500px",
        height: "330px",
        inline: true,
        href: "#" + PopUpDiv,
        onComplete: function () {
            InitAddCardDetailsDataCalendars();
            $("#" + PopUpDiv).show();
        },
        onClosed: function () {
            $("#" + PopUpDiv).hide();
        }
    });
}
$(document).on('click', '#CardAddBtn', function () {
    var $form = $('#AddNewCardForm');
    if ($form.valid()) {
        CardValidationClientSideHide = false;
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: $form.serialize(),
            beforeSend: function (xhr) {
                xhr.overrideMimeType('text/plain; charset=x-user-defined');
            },
            success: function (data) {
                if (data.indexOf("Error") != -1)
                    jAlert(data, "Error");
            },
            error: function (xhr) {
                jAlert(xhr.statusText, "Error");
            },
            complete: function () {
                $('#CardAddBtn').removeClass('BackColorRed')
                jAlert("Data SuccessFully Saved:", "Successful");
                $('#cboxClose').click();
                IsDeleteView = false;
                LoadCardGrid();
            }
        });
    }
    else
        CardValidationClientSideHide = true;
});
$(document).on('click', '#CardDetailsSaveBtn', function () {
    var $form = $('#LoadCardDetailsForm');
    if ($form.valid()) {
        if ($form[0].length > 0) {
            $.ajax({
                url: $form.attr('action'),
                type: $form.attr('method'),
                data: $form.serialize(),
                beforeSend: function (xhr) {
                    xhr.overrideMimeType('text/plain; charset=x-user-defined');
                },
                success: function (data) {
                    if (data.indexOf("Error") != -1)
                        jAlert(data, "Error");
                },
                error: function (xhr) {
                    jAlert(xhr.statusText, "Error");
                },
                complete: function () {
                    $('#CardDetailsSaveBtn').removeClass('BackColorRed')
                    jAlert("Data SuccessFully Saved:", "Successful");
                    IsDeleteView = false;
                    LoadCardGrid();
                }
            });
        }
        else
            jAlert("You have not data to save:", "Attention!");
    }
});
function LoadCardGrid() {
    var SetupCardsGridViewModel = {
        SelectedCardTypeIDText: $("#SelectedCardTypeIDText").val(),
        CardNumberText: $("#CardNumberText").val(),
        PlaceHolderNameText: $("#PlaceHolderNameText").val(),
        IsDelete: IsDeleteView,
        CardID: parseInt(CardIDView),
        PageNum: parseInt(PageNumber),
        IsSearch: IsSearchView,
        IsActiveSearch: $("#IsActiveSearch").val(),
    };

    var DTO = JSON.stringify(SetupCardsGridViewModel);
    $.ajax({
        url: urls["SetupLoadCardsGrid"],
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: DTO,
        success: function (data) {
            $("#SetupCardGrid").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            InitCardDetailsDataCalendars();
            CardTypeDrop();
        }
    });
}
function CardTypeDrop() {
    $(".CardTypeDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
        var tdparent = $(elem).next().parent();
        var trparent = tdparent.parent();
        if (trparent.find(".RoomGridDropHide").find("option:selected").text() == "Amex")
            trparent.find(".CreditCard").removeClass("CreditCard").addClass("CreditCardAmex");
        if (trparent.find(".RoomGridDropHide").find("option:selected").text() == "Visa")
            trparent.find(".CreditCard").removeClass("CreditCard").addClass("CreditCardVisa");
        if (trparent.find(".RoomGridDropHide").find("option:selected").text() == "Master Card")
            trparent.find(".CreditCard").removeClass("CreditCard").addClass("CreditCardMasterCard");
        if (trparent.find(".RoomGridDropHide").find("option:selected").text() == "Check")
            trparent.find(".CreditCard").removeClass("CreditCard").addClass("CreditCardCheck");
      
    });
}
$(document).on('change', '.CardTypeDrop', function () {
    $(".CardTypeDrop").each(function (index, elem) {
        var tdparent = $(elem).parent();
        var trparent = tdparent.parent();
        var OldCreditCardType = trparent.find(".RoomGridDropHide").find("option:selected").text();
        if (OldCreditCardType == "Master Card")
            OldCreditCardType="MasterCard"
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
        var NewCreditCardType = trparent.find(".RoomGridDropHide").find("option:selected").text();
        if (NewCreditCardType == "Master Card")
            NewCreditCardType = "MasterCard"
        trparent.find(".CreditCard" + OldCreditCardType).removeClass("CreditCard" + OldCreditCardType).addClass("CreditCard" + NewCreditCardType);
        if ($(this).closest("form").valid()) {
            $(this).closest("form").find("#errorMessageClient").text("");
            var elements = "#" + $(this).closest("form").attr("id") + " .table_inputs_Unvalidated";
            $(elements).not('label').each(function () {
                if ($(this).valid())
                    $(this).removeClass('table_inputs_Unvalidated');
            });
        }
        else
            $(this).closest("form").find("#errorMessageServer").hide();
    });
});
$(document).on('change', '.AddCardTypeDrop', function () {
    $(".AddCardTypeDrop").each(function (index, elem) {
        var divparent = $(elem).parent().parent().parent().parent();
        var OldCreditCardType = divparent.find(".RoomGridDropHide").find("option:selected").text();
        if (OldCreditCardType == "Master Card")
            OldCreditCardType = "MasterCard"
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
        var NewCreditCardType = divparent.find(".RoomGridDropHide").find("option:selected").text();
        if (NewCreditCardType == "Master Card")
            NewCreditCardType = "MasterCard"
        divparent.find(".CreditCard" + OldCreditCardType).removeClass("CreditCard" + OldCreditCardType).addClass("CreditCard" + NewCreditCardType);
        $(this).closest("form").valid();
    });
});

function InitCardDetailsDataCalendars() {

    $(".CardDeteilsDataCalendar").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 5
            });
        },
    });
}

function InitAddCardDetailsDataCalendars() {

    $("#AddCardDeteilsDataCalendar").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 999999
            });
        }
    });
}

// text element complete text 
$(document).on('input', '.QuotaTxtComplete', function () {
    if (CardTimerId == null) {
        CardAutoComElem = $(this).attr('id');
        CardAutoComElemVal = $("#" + CardAutoComElem).val();
        CardTimerId = setInterval(function () {

            var keyword = $("#" + CardAutoComElem).val();
            if (keyword == CardAutoComElemVal) {
                var PropName = "";
                if (CardAutoComElem.indexOf("CardNumberText") != -1)
                    PropName = "CardNumberText";
                if (CardAutoComElem.indexOf("PlaceHolderNameText") != -1)
                    PropName = "PlaceHolderNameText";

                var position = $("#" + CardAutoComElem).offset();
                position.top = position.top + $("#" + CardAutoComElem).height() + 5;
                $.ajax({
                    url: urls["SetupAutoComplete"],
                    data: { 'PropName': PropName, 'keyword': keyword },
                    type: 'POST',
                    success: function (data) {
                        $("#AutoCompleteDiv").html(data);
                        var width = $("#" + CardAutoComElem).css("width");
                        $("#AutoCompleteDiv").css("width", width);
                        $("#AutoCompleteDiv").show();
                        $("#AutoCompleteDiv").offset(position);
                    },
                    error: function (xhr) {
                        jAlert(xhr.statusText, "Error");
                    },
                    complete: function () {
                        clearInterval(CardTimerId);
                        CardTimerId = null;
                    }
                });
            }
            else
                CardAutoComElemVal = keyword;
        }, 600);
    }
});
$(document).on('click', '.QuotaAutoCompleteDivClose', function () {
    $(this).parent().parent().hide();
});
function htmlDecode(value) {
    return $('<div/>').html(value).text();
}
function AutoCompleteRowClick(key, val) {
    val = htmlDecode(val);
    $("#" + CardAutoComElem).val(val);
    if (CardAutoComElem.indexOf("CardNumberText") != -1)
        $("#" + CardAutoComElem).next().val(key);
    if (CardAutoComElem.indexOf("PlaceHolderNameText") != -1)
        $("#" + CardAutoComElem).next().val(key);
    $("#AutoCompleteDiv").hide();
}

var originalClose = $.colorbox.close;
$.colorbox.close = function () {
    if ($('#CardAddBtn').hasClass('BackColorRed')) {
        jConfirm(Messages["ClosePopUp"], Messages["ClosePopUpTitle"], function (retVal) {
            if (retVal == true) {
                $("#AddNewCardForm").empty();
                LoadCardGrid();
                originalClose();
            }
        });
    }
    else {
        $("#AddNewCardForm").empty();
        LoadCardGrid();
        originalClose();
    }
};
$(document).on('change', '.ElementsForValidation', function () {
    if ($(this).valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
    if (CardValidationClientSideHide) {
        if ($(this).closest("form").valid()) {
            $(this).closest("form").find("#errorMessageClient").text("");
        }
    }
    else if ($(this).valid()) {
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            $(this).valid();
        });
    }
});
$(document).on('change', '.ForValidation', function () {
    if ($(this).valid)
        $(this).removeClass('table_inputs_Unvalidated');
    if ($(this).closest("form").valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            if ($(this).valid())
                $(this).removeClass('table_inputs_Unvalidated');
        });
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
});
